package com.extr.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.extr.controller.domain.AnswerSheetItem;
import com.extr.controller.domain.HomeWorkCreatorParam;
import com.extr.controller.domain.HomeWorkReviewFinishParam;
import com.extr.controller.domain.Message;
import com.extr.controller.domain.QuestionQueryResult;
import com.extr.controller.domain.TeacherReadSheetItem;
import com.extr.domain.exam.HomeWork;
import com.extr.domain.exam.HomeWorkHistory;
import com.extr.domain.question.Field;
import com.extr.domain.user.User;
import com.extr.security.UserInfo;
import com.extr.service.HomeWorkService;
import com.extr.service.QuestionService;
import com.extr.service.UserService;
import com.extr.util.Page;
import com.extr.util.PagingUtil;
import com.extr.util.QuestionAdapter;
import com.extr.util.xml.Object2Xml;

//作业管理控制器
@Controller
public class HomeWorkController {

	@Autowired
	private HomeWorkService homeWorkService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private UserService userService;
	
	private static final String SUCCESS_Message = "success";
	private static final String failed_Message = "failed";
	
	@RequestMapping(value = "/admin/homework-add", method = RequestMethod.GET)
	public String exampaperAddPage(Model model) {
		//获取知识点范围
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		return "admin/homework-add";
	}
	
	@RequestMapping(value = "/admin/homework-list", method = RequestMethod.GET)
	public String homeworkListPage(Model model,
			HttpServletRequest httpServletRequest) {
		return "redirect:homeworkfilter-1.html";
	}

	@RequestMapping(value = "/admin/homeworkfilter-{page}.html", method = RequestMethod.GET)
	public String homeworkListFilterPage(Model model,
			@PathVariable("page") int page) {

		Page<HomeWork> pageModel = new Page<HomeWork>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(10);
		List<HomeWork> homework = homeWorkService.getHomeWorkList(pageModel);
		String pageStr = PagingUtil.getPageBtnlink(page,pageModel.getTotalPage(),pageModel.getTotalRecord());
		model.addAttribute("homework", homework);
		model.addAttribute("pageStr", pageStr);
		return "admin/homework-list";
	}
	
	/**
	 * 创建电子作业
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "admin/homework-add", method = RequestMethod.POST)
	public @ResponseBody
	Message createHomeWork(@RequestBody HomeWorkCreatorParam param) {

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		Message message = new Message();
		HomeWork homeWork = new HomeWork();
		homeWork.setName(param.getPaperName());
		homeWork.setDuration(param.getTime());
		homeWork.setPass_point(param.getPassPoint());
		homeWork.setCreator(userInfo.getUsername());
		homeWork.setTotal_point(param.getPaperPoint());
		//手工布置作业
		//if(param.getQuestionKnowledgePointRate().size() == 0){
		try{
			homeWorkService.insertHomeWork(homeWork);
		}catch(Exception ex){
			message.setResult(ex.getMessage());
		}
		message.setGeneratedId(homeWork.getId());
		return message;
		//}
		/*  //预留自动布置题库试题作业
		List<Integer> idList = new ArrayList<Integer>();
		HashMap<Integer, Float> knowledgeMap = param
				.getQuestionKnowledgePointRate();
		Iterator<Integer> it = knowledgeMap.keySet().iterator();
		while(it.hasNext()){
			idList.add(it.next());
		}
		HashMap<Integer, HashMap<Integer, List<QuestionStruts>>> questionMap = questionService.getQuestionStrutsMap(idList);
		try{
			homeWorkService.createHomeWork(questionMap, param.getQuestionTypeNum(),
					param.getQuestionTypePoint(),
					param.getQuestionKnowledgePointRate(), homeWork);
			message.setGeneratedId(homeWork.getId());
		}catch(Exception e){
			e.printStackTrace();
			message.setResult(e.getMessage());
		}
		return message;
		*/
	}
	
	/**
	 * 预览电子作业
	 * @param model
	 * @param homeworkid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/homework-preview/{homeworkid}", method = RequestMethod.GET)
	public String exampaperPreviewPage(Model model,
			@PathVariable("homeworkid") int homeworkid,HttpServletRequest request) {
		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		HomeWork homeWork = homeWorkService.getHomeWorkById(homeworkid);
		StringBuilder sb = new StringBuilder();
		if(homeWork.getContent() != null && !homeWork.getContent().equals("")){
			List<QuestionQueryResult> questionList = Object2Xml.toBean(homeWork.getContent(), List.class);
			for(QuestionQueryResult question : questionList){
				/*AnswerSheetItem as = new AnswerSheetItem();
				as.setAnswer(question.getAnswer());
				as.setQuestion_type_id(question.getQuestionTypeId());
				as.setPoint(question.getQuestionPoint());*/
				QuestionAdapter adapter = new QuestionAdapter(question,strUrl);
				sb.append(adapter.getStringFromXML());
			}
		}
		model.addAttribute("htmlStr", sb);
		model.addAttribute("homeworkid", homeworkid);
		model.addAttribute("homeworkname", homeWork.getName());
		return "admin/homework-preview";
	}
	
	/**
	 * 打开学生作业准备阅卷
	 * @param model
	 * @param homeWorkId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/homework-review/{homeWorkHistId}", method = RequestMethod.GET)
	public String homeworkReviewPage(Model model, @PathVariable("homeWorkHistId") int homeWorkHistId, HttpServletRequest request) {
		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		HomeWorkHistory homeWorkHistory = homeWorkService.getUserHomeWorkHistoryByHistId(homeWorkHistId);
		int homeWorkId = homeWorkHistory.getHomeWorkId();
		User user = userService.getUserById(homeWorkHistory.getUserId());
		HomeWork homeWork = homeWorkService.getHomeWorkById(homeWorkId);
		StringBuilder sb = new StringBuilder();
		if(homeWorkHistory.getContent() != null && !homeWorkHistory.getContent().equals("")){
			List<QuestionQueryResult> questionList = Object2Xml.toBean(homeWorkHistory.getContent(), List.class);
			HashMap<Integer, AnswerSheetItem> hm = Object2Xml.toBean(homeWorkHistory.getAnswerSheet(), HashMap.class);
			for(QuestionQueryResult question : questionList){
				/*AnswerSheetItem as = new AnswerSheetItem();
				as.setAnswer(question.getAnswer());
				as.setQuestion_type_id(question.getQuestionTypeId());
				as.setPoint(question.getQuestionPoint());*/
				QuestionAdapter adapter = new QuestionAdapter(hm.get(question.getQuestionId()), question, strUrl);
				sb.append(adapter.getTeacherReviewStringFromXML());
			}
		}
		model.addAttribute("htmlStr", sb.toString());
		model.addAttribute("homeWorkId", homeWorkId);
		model.addAttribute("homeWorkHistId", homeWorkHistId);
		model.addAttribute("homeWorkName", homeWork.getName());
		model.addAttribute("truename", user.getTruename());
		model.addAttribute("username", user.getUsername());
		//跳转到评阅学生作业页面
		return "admin/homework-teacher-review";
	}
	
	/**
	 * 老师提交阅卷结果
	 * @param hfp
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "admin/homework-review-submit", method = RequestMethod.POST)
	public @ResponseBody
	Message finishReviewHomeWork(@RequestBody HomeWorkReviewFinishParam hrp) {
		Message message = new Message();
		try {
			HomeWorkHistory homeWorkHistory = homeWorkService.getUserHomeWorkHistoryByHistId(hrp.getHomework_history_id());
			List<QuestionQueryResult> questionList = Object2Xml.toBean(homeWorkHistory.getContent(), List.class);
			float pointGet = 0f;
			HashMap<Integer, TeacherReadSheetItem> hm = hrp.getTs();
			//累计手工评分
			Iterator iter = hm.entrySet().iterator();
			while(iter.hasNext()) {
				Map.Entry entry = (Map.Entry)iter.next();
				//Object key = entry.getKey();
				TeacherReadSheetItem teacherReadSheetItem = (TeacherReadSheetItem) entry.getValue();
				pointGet += teacherReadSheetItem.getPoint();
			}
			/*System.out.println("系统评分累计得："+homeWorkHistory.getPointSysGet());
			System.out.println("手工评分累计得："+pointGet);
			System.out.println("系统评分+手工评分："+(homeWorkHistory.getPointSysGet()+pointGet));*/
			/*for(QuestionQueryResult qqr : questionList){
				if(hrp.getTs().get(qqr.getQuestionId()) != null)
					pointGet += hrp.getTs().get(qqr.getQuestionId()).getPoint();
			}*/
			//计算得分
			homeWorkHistory.setPointGet(homeWorkHistory.getPointSysGet()+pointGet);
			homeWorkHistory.setTeacherReadSheet(Object2Xml.toXml(hrp.getTs()));
			homeWorkHistory.setIsRead(1); //状态修改为已经批阅
			//homeWorkHistory.setSubmitTime(new Date());
			homeWorkService.updateHomeWorkHistoryOfTeacher(homeWorkHistory);
		} catch (Exception e) {
			e.printStackTrace();
			message.setResult(e.getClass().getName());
		}
		return message;
	}
	
	/**
	 * 跳转至学生提交的作业列表
	 * @param model
	 * @param homeWorkId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/admin/homeworkreviewfilter-{homeWorkId}-{page}.html", method = RequestMethod.GET)
	public String homeworkReviewListFilterPage(Model model,
			@PathVariable("homeWorkId") int homeWorkId,
			@PathVariable("page") int page) {
		Page<HomeWorkHistory> pageModel = new Page<HomeWorkHistory>();
		pageModel.setPageNo(page);
		pageModel.setPageSize(10);
		List<HomeWorkHistory> homeWorkHistList = homeWorkService.getHomeWorkHistByHomeWorkId(homeWorkId, pageModel);
		String pageStr = PagingUtil.getPageBtnlink(page, pageModel.getTotalPage());
		model.addAttribute("homeWorkId", homeWorkId);
		model.addAttribute("homeWorkHistList", homeWorkHistList);
		model.addAttribute("pageStr", pageStr);
		return "admin/homework-review";
	}
	
	/**
	 * 跳转到给作业添加题目的页面
	 * @param model
	 * @param homeworkid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/homework-edit/{homeworkid}", method = RequestMethod.GET)
	public String homeworkEditPage(Model model,
			@PathVariable("homeworkid") int homeworkid,HttpServletRequest request) {
		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		HomeWork homeWork = homeWorkService.getHomeWorkById(homeworkid);
		StringBuilder sb = new StringBuilder();
		if(homeWork.getContent() != null && !homeWork.getContent().equals("")){
			List<QuestionQueryResult> questionList = Object2Xml.toBean(homeWork.getContent(), List.class);
			for(QuestionQueryResult question : questionList){
				/*AnswerSheetItem as = new AnswerSheetItem();
				as.setAnswer(question.getAnswer());
				as.setQuestion_type_id(question.getQuestionTypeId());
				as.setPoint(question.getQuestionPoint());*/
				QuestionAdapter adapter = new QuestionAdapter(question,strUrl);
				sb.append(adapter.getStringFromXML());
			}
		}
		model.addAttribute("htmlStr", sb);
		model.addAttribute("homeworkid", homeworkid);
		model.addAttribute("homeworkname", homeWork.getName());
		return "admin/homework-edit";
	}
	
	/**
	 * 给作业添加试题
	 * @param model
	 * @param homeworkid
	 * @param questionPointMap
	 * @return
	 */
	@RequestMapping(value = "/admin/update-homework/{homeworkid}", method = RequestMethod.POST)
	public @ResponseBody
	Message exampaperOnUpdate(Model model,
			@PathVariable("homeworkid") int homeworkid,
			@RequestBody HashMap<Integer, Float> questionPointMap) {
		Message message = new Message();
		try{
			HomeWork homework = new HomeWork();
			List<Integer> idList = new ArrayList<Integer>();
			Iterator<Integer> it = questionPointMap.keySet().iterator();
			float sum = 0;
			while(it.hasNext()){
				int key = it.next();
				idList.add(key);
			}
			List<QuestionQueryResult> questionList = homeWorkService.getQuestionDescribeListByIdList(idList);
			for(QuestionQueryResult q : questionList){
				q.setQuestionPoint(questionPointMap.get(q.getQuestionId()));
				sum += questionPointMap.get(q.getQuestionId());
			}
			String content = Object2Xml.toXml(questionList);
			homework.setContent(content);
			homework.setTotal_point(sum);
			homework.setId(homeworkid);
			homeWorkService.updateHomeWork(homework);
		}catch(Exception e){
			message.setResult(e.getLocalizedMessage());
		}
		return message;
	}
	
	/**
	 * 发布作业
	 * @param homeWorkId
	 * @return
	 */
	@RequestMapping(value = "admin/work-publish", method = RequestMethod.POST)
	public @ResponseBody Message publishHomeWork(@RequestBody Integer homeWorkId){
		Message message = new Message();
		HomeWork homeWork = new HomeWork();
		homeWork.setId(homeWorkId);
		homeWork.setStatus(1);
		try{
			homeWorkService.updateHomeWork(homeWork);
		}catch(Exception e){
			message.setResult(e.getClass().getName());
		}
		return message;
	}
	
	/**
	 * 下线作业
	 * @param homeWorkId
	 * @return
	 */
	@RequestMapping(value = "admin/work-offline", method = RequestMethod.POST)
	public @ResponseBody Message offlineHomeWork(@RequestBody Integer homeWorkId){
		Message message = new Message();
		HomeWork homeWork = new HomeWork();
		homeWork.setId(homeWorkId);
		homeWork.setStatus(2);
		try{
			homeWorkService.updateHomeWork(homeWork);
		}catch(Exception e){
			message.setResult(e.getClass().getName());
		}
		return message;
	}
	
	/**
	 * 删除作业
	 * @param homeWorkId
	 * @return
	 */
	@RequestMapping(value = "admin/work-delete", method = RequestMethod.POST)
	public @ResponseBody Message deleteHomeWork(@RequestBody Integer homeWorkId){
		Message message = new Message();
		try{
			HomeWork homeWork = homeWorkService.getHomeWorkById(homeWorkId);
			if(homeWork.getStatus() == 1){
				message.setResult("已发布的作业不允许删除");
				return message;
			}
			homeWorkService.deleteHomeWork(homeWorkId);
		}catch(Exception e){
			message.setResult(e.getClass().getName());
		}
		return message;
	}
}
